package com.ruoyi.web.controller.system;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.ClientUtils;
import com.ruoyi.common.OrderNumUtil;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.ShankHandUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.app.Device;
import com.ruoyi.system.domain.app.DeviceSpace;
import com.ruoyi.system.domain.app.PowerBilling;
import com.ruoyi.system.domain.app.QrRecord;
import com.ruoyi.system.domain.vo.SocketVo;
import com.ruoyi.system.mapper.app.DeviceMapper;
import com.ruoyi.system.mapper.app.DeviceSpaceMapper;
import com.ruoyi.system.mapper.app.QrRecordMapper;
import com.ruoyi.system.service.DeviceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Api(tags = "设备相关")
@RestController
@RequestMapping()
public class DeviceController extends BaseController {
    
    
    @Autowired
    DeviceService deviceService;

    @Autowired
    QrRecordMapper qrRecordMapper;

    @Autowired
    DeviceMapper deviceMapper;

    @Autowired
    DeviceSpaceMapper deviceSpaceMapper;

    @Autowired
    ShankHandUtils shankHandUtils;

    @ApiOperation("获取区域上微信支付信息")
    @PreAuthorize("@ss.hasPermi('system:dept:wx:info')")
    @GetMapping("/dept/wx/info")
    public AjaxResult getDeptWxInfo(@RequestParam Long deptId){
        return AjaxResult.success(deviceService.getDeptWxInfo(deptId));
    }

    @ApiOperation("修改区域上微信支付信息")
    @PreAuthorize("@ss.hasPermi('system:dept:wx:set')")
    @PostMapping("/dept/wx/set")
    public AjaxResult DeptWxSet(@RequestParam Long deptId,String appId,String appSecret,String mchId,String wxKey){
        deviceService.setDeptWxInfo(deptId,appId,appSecret,mchId,wxKey);
        return AjaxResult.success();
    }



    @ApiOperation(value = "设备绑定小区",notes = "system:device:bind:community")
    @PreAuthorize("@ss.hasPermi('system:device:bind:community')")
    @PutMapping("/device/bind/community")
    public AjaxResult deviceBindCommunity(@RequestParam Long communityId,@RequestParam String deviceNum){
        deviceService.deviceBindCommunity(communityId,deviceNum);
        return AjaxResult.success();
    }

    @ApiOperation("设备解绑小区")
    @PreAuthorize("@ss.hasPermi('system:device:unbind:community')")
    @PutMapping("/device/unbind/community")
    public AjaxResult deviceUnBindCommunity(@RequestParam Long deviceId){
        deviceService.deviceUnBindCommunity(deviceId);
        return AjaxResult.success();
    }
    
    
    @ApiOperation(value = "获取设备功率段选项",notes = "system:power:billing")
    @PreAuthorize("@ss.hasPermi('system:power:billing')")
    @GetMapping("/power/billing")
    public AjaxResult getPowerBilling(@RequestParam Long deviceId){
        return AjaxResult.success(deviceService.getPowerBilling(deviceId));
    }

    @ApiOperation(value = "重置设备功率段选项",notes = "system:power:billing:reset")
    @PreAuthorize("@ss.hasPermi('system:power:billing:reset')")
    @PostMapping("/power/billing")
    public AjaxResult resetPowerBilling(@RequestBody List<PowerBilling> powerBillings){
        deviceService.resetPowerBilling(powerBillings);
        return AjaxResult.success();
    }

    @ApiOperation(value = "添加设备",notes = "system:device:add")
    @PreAuthorize("@ss.hasPermi('system:device:add')")
    @PostMapping("/add/device")
    public AjaxResult addDevice(@RequestParam String deviceNum,Long communityId,String communityName, String latitude,String longitude,
                                @RequestParam String site,Integer billingType,String deviceName,String remark,Long operatorId,String operatorName,String deviceType){
        Device device = new Device();
        device.setDeviceNum(deviceNum.trim());
        device.setCommunityId(communityId);
        device.setCommunityName(communityName);
        device.setOperatorId(operatorId);
        device.setOperatorName(operatorName);
        device.setSite(site);
        device.setBillingType(billingType);
        device.setDeviceName(deviceName);
        device.setRemark(remark);
        deviceService.addDevice(device);
        return AjaxResult.success();
    }

    @ApiOperation(value = "删除设备",notes = "system:device:del")
    @PreAuthorize("@ss.hasPermi('system:device:del')")
    @DeleteMapping("/del/device")
    public AjaxResult delDevice(@RequestParam Long id){
        deviceService.delDevice(id);
        return AjaxResult.success();
    }

    @ApiOperation(value = "修改设备",notes = "system:device:set")
    @PreAuthorize("@ss.hasPermi('system:device:set')")
    @PutMapping("/set/device")
    public AjaxResult setDevice(@RequestBody Device device){

        deviceService.setDevice(device);
        return AjaxResult.success();
    }

    @ApiOperation("导出随机插座编号")
    @PreAuthorize("@ss.hasPermi('system:random:import')")
    @PutMapping("/socket/random/import")
    @RepeatSubmit
    public AjaxResult socketRandomImport(@RequestParam Integer amount){
        List<SocketVo> socketVos = new ArrayList<>(amount);
//        for (int i = 0;i < amount;i++) {
//            SocketVo socketVo = new SocketVo();
//            socketVo.setSocketNo(OrderNumUtil.getRandom());
//            socketVos.add(socketVo);
//        }
        List<QrRecord> qrRecords = qrRecordMapper.selectAll();
        if(qrRecords.size() ==0){
            throw new ServiceException("没有初始化二维码");
        }
        String end_num = qrRecords.get(0).getEnd_num();
        int end =  Integer.valueOf(end_num);
        int j = end;
        int start =end;

        for (int i = j; i < amount+end; i++) {
            j += 1;
            SocketVo socketVo = new SocketVo();
            socketVo.setSocketNo(String.valueOf(j));
            socketVos.add(socketVo);
        }

        QrRecord qrRecord = new QrRecord();
        qrRecord.setQrcode_count(amount.toString());
        qrRecord.setCreate_by(SecurityUtils.getLoginUser().getUsername());
        qrRecord.setCreate_time(new Date());
        qrRecord.setStart_num(String.valueOf(start+1));
        qrRecord.setEnd_num(String.valueOf(j));

        qrRecordMapper.insertSelective(qrRecord);

        //ExcelUtil<SocketVo> util = new ExcelUtil<SocketVo>(SocketVo.class);
       // return util.exportExcel(socketVos,"随机插座列表");
        return AjaxResult.success(qrRecord);
    }

    @ApiOperation("查询生成二维码记录")
    @GetMapping("/socket/product/record")
    public AjaxResult Qrecord(){
        startPage();
        return AjaxResult.success(getDataTable(qrRecordMapper.selectList()));
    }

    @ApiOperation("初始化二维码")
    @PostMapping("/socket/qrcode/init")
    @RepeatSubmit
    public AjaxResult qrcodeInit(@RequestParam String initNum){
        if(qrRecordMapper.selectList().size() !=0){
            throw new ServiceException("二维码已有初始化");
        }
        QrRecord qrRecord = new QrRecord();
        Integer end = Integer.valueOf(initNum)-1;
        qrRecord.setCreate_by(SecurityUtils.getUsername());
        qrRecord.setCreate_time(new Date());
        qrRecord.setEnd_num(end.toString());
        qrRecordMapper.insertSelective(qrRecord);
        return AjaxResult.success();
    }

    @ApiOperation("插座绑定二维码")
    @PreAuthorize("@ss.hasPermi('system:bind:qc')")
    @PutMapping("/socket/bind/qc")
    public AjaxResult socketBindQc(@RequestParam Long deviceId,@RequestParam String socketNo,
                                   @RequestParam String qcCode){
       deviceService.socketBindQc(deviceId,socketNo,qcCode);
       return AjaxResult.success();
    }

    @ApiOperation(value = "设备设备参数并更新",notes = "system:device:setconfig")
    @PreAuthorize("@ss.hasPermi('system:device:setconfig')")
    @PutMapping("/set/device-config")
    public AjaxResult setDeviceConfig(@RequestBody Device device){
        return deviceService.setDeviceConfig(device);
    }

    @ApiOperation(value = "设备重启",notes = "system:device:restart")
    @PreAuthorize("@ss.hasPermi('system:device:restart')")
    @PostMapping("/set/restart")
    public AjaxResult setDeviceRestart(@RequestParam String deviceNum){
        deviceService.setDeviceRestart(deviceNum);
        return AjaxResult.success();
    }

    @ApiOperation(value = "设备列表",notes = "system:device:list")
    @PreAuthorize("@ss.hasPermi('system:device:list')")
    @GetMapping("/device/list")
    public AjaxResult deviceList(String deviceNum,String deviceName,String communityName,Long communityId){
        Device device = new Device();
        device.setDeviceNum(deviceNum);
        device.setDeviceName(deviceName);
        device.setCommunityName(communityName);
        device.setCommunityId(communityId);
        startPage();
        return AjaxResult.success(getDataTable(deviceService.deviceList(device)));
    }

    @ApiOperation(value = "获取设备下插座列表",notes = "system:device:space:list")
    @PreAuthorize("@ss.hasPermi('system:device:space:list')")
    @GetMapping("/device/space/list")
    public AjaxResult deviceSpaceList(@RequestParam Long deviceId){
        return AjaxResult.success(deviceService.deviceSpaceList(deviceId));
    }

//    @ApiOperation(value = "远程开门",notes = "system:device:open   type 1开小门传holeNum  0开大门")
//    @PreAuthorize("@ss.hasPermi('system:device:open')")
//    @GetMapping("/device/open/door")
//    public AjaxResult deviceOpenDoor(@RequestParam String deviceNum, Integer holeNum, Integer type){
//        deviceService.deviceOpenDoor(deviceNum,holeNum,type);
//        return AjaxResult.success();
//    }

//    @ApiOperation(value = "远程禁用电仓",notes = "system:hole:state holeNum小仓门  holeState 0启用 1禁用  ")
//    @PreAuthorize("@ss.hasPermi('system:hole:state')")
//    @GetMapping("/hole/state")
//    public AjaxResult holeState(@RequestParam String deviceNum,@RequestParam Integer holeNum,Integer holeState){
//        deviceService.holeState(deviceNum,holeNum,holeState);
//        return AjaxResult.success();
//    }

    @ApiOperation(value = "远程重启",notes = "system:open:restart ")
    @GetMapping("/charge/restart")
    public AjaxResult chargeRestart(@RequestParam String deviceNum){
        deviceService.chargeRestart(deviceNum);
        return AjaxResult.success();
    }

    @ApiOperation("获取设备 事件 报警")
    @PreAuthorize("@ss.hasPermi('system:device:warning:list')")
    @GetMapping("/device/warning/list")
    public AjaxResult deviceWarningList(@RequestParam String deviceNum){
        startPage();
        return AjaxResult.success(getDataTable(deviceService.deviceWarningList(deviceNum)));
    }

    @ApiOperation(value = "手动充电",notes = "")
    @GetMapping("/device/manual/recharge")
    @RepeatSubmit
    public AjaxResult deviceManualRecharge(@RequestParam String deviceNum, @RequestParam Integer chargeTime, @RequestParam Integer socketNo){
        Device device = deviceMapper.selectByNum(deviceNum);
        DeviceSpace deviceSpace = deviceSpaceMapper.selectBySpaceId(device.getId(), socketNo);
        if(deviceSpace.getState()==1){
            return  AjaxResult.error("插座正在使用中！");
        }
        deviceService.createRecharge(deviceNum, chargeTime, socketNo);
        return AjaxResult.success();
    }
    @ApiOperation(value = "测试充电",notes = "")
    @GetMapping("/device/test/recharge")
    @RepeatSubmit
    public AjaxResult testRecharge(@RequestParam String deviceNum,@RequestParam String socketNo){
        Device device = deviceMapper.selectByNum(deviceNum);
        DeviceSpace deviceSpace = deviceSpaceMapper.selectBySpaceId(device.getId(), Integer.valueOf(socketNo));
        if (deviceSpace.getState() != 0) {
            return AjaxResult.error("插座忙碌中或故障");
        }
        shankHandUtils.checkStatus(deviceNum);
        JSONObject jsonObject = null;
        try {
            jsonObject = ClientUtils.doGetMethod("http://localhost:8610/start/pay/charge?orderNo=" + OrderNumUtil.getOrderNum()
                    + "&orderMoney=" + new BigDecimal("0.01")
                    + "&deviceNum=" + deviceNum
                    + "&socketNo=" + socketNo
                    );

        } catch (IOException e) {
            e.printStackTrace();
        }
        if (StringUtils.isNull(jsonObject) || !"200".equals(jsonObject.getString("code"))) {
            throw new ServiceException("充电失败！请稍后再试。");
        }
        return AjaxResult.success();

    }

}
